package picoevo.tutorials.simbad.robotavoidbehavior;

import picoevo.core.evolution.EvaluationOperator_Individual;
import picoevo.ext.representation.Element_StaticArray_Double;
import picoevo.ext.representation.Individual_SimpleIndividual;
import picoevo.toolbox.Display;
import simbad.gui.Simbatch;

public class EvaluationOperator_SimpleAvoiderRobot extends EvaluationOperator_Individual {

	// ### Constructors ###

	public EvaluationOperator_SimpleAvoiderRobot() {
		super();
	}

	public EvaluationOperator_SimpleAvoiderRobot(String __name) {
		super(__name);
	}

	// ### Methods ###

	@Override
	public void evaluate(Object __o) {
		super.evaluate(__o);

		try {
			Individual_SimpleIndividual individual = (Individual_SimpleIndividual) __o;

			double maxOne = 0;

			individual.setFitness(computeFitness(individual));
		} catch (java.lang.ClassCastException e) {
			Display.error("" + this.getClass().getName() + "::evaluate(.) - Class cast exception");
		}
	}

	private double computeFitness(Individual_SimpleIndividual __individual) {
		Simbatch simulator = (Simbatch) __individual.getTemplate().getObjectProperty("Simulator");
		Evaluator_SimpleAvoiderRobot robot = (Evaluator_SimpleAvoiderRobot) __individual.getTemplate().getObjectProperty("Robot");

		simulator.reset(); // stability test?
		robot.setGenome((double[]) ((Element_StaticArray_Double) __individual.getElementAt(0)).getArray());
		robot._myRobot.resetEvaluation();

		int i = 0;
		while (i < 10000 && ((Evaluator_SimpleAvoiderRobot) __individual.getTemplate().getObjectProperty("Robot"))._isRunnable == true) {
			((Simbatch) __individual.getTemplate().getObjectProperty("Simulator")).step();
			i++;
		}

		// Display.info("fitness is " +
		// __individual.getTemplate().getRobot()._fitness + "");
		// Display.info(" value + " with genome : " );
		// for ( int j = 0 ; j < genome.length ; j++ )
		// System.out.print( genome[j] + " ; " );
		// Display.info("");

		return (robot._fitness);
	}

}
